import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;

    public String toString() {
        return "Message{from = " + from + ", to = " + to + ", message = " + message + "}";
    }
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    List<Message> list = new ArrayList<>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1 . 读取前端发来的数据 保存到服务器

//        req.getInputStream()    用于从客户端读取 HTTP 请求的主体内容
//        ObjectMapper.readValue 方法用于将 JSON 数据反序列化为 Java 对象。
//        结合 req.getInputStream() 方法，我们可以将 HTTP 请求的 JSON 数据直接转换为 Java 对象。
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);

        resp.setStatus(200);
        resp.setContentType("application/json");
        resp.getWriter().write("{ OK : true ! } ");
        list.add(message);
        System.out.println("收到了请求: " + list );

    }

//        2 . 把服务器的数据拿回到客户端页面上显示出来
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        通过这个方法来处理当前获取消息列表的 get 请求, 不需要解析参数, 直接返回数据即可.
        resp.setStatus(200);
        resp.setContentType("application/json; charset = utf-8");
        String s = objectMapper.writeValueAsString(list);
        resp.getWriter().write(s);
    }
}
